package edu.bit.water.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.mapping.ResultMapping;
import org.apache.juli.ClassLoaderLogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;

import edu.bit.water.dao.EntityEvaCtestSumDao;
import edu.bit.water.dao.LabelEvaCtestSumDao;
import edu.bit.water.dao.MetaEvaCtestSumDao;
import edu.bit.water.entity.Column;
import edu.bit.water.entity.LabelEvaCtestSum;
import java.text.DecimalFormat;
import java.text.*;

@Service
public class LabelEvaCtestSumService {

	@Autowired
	private LabelEvaCtestSumDao labelEvaCtestSumDao;
	@Autowired
	private EntityEvaCtestSumDao entityEvaCtestSumDao;
	@Autowired
	private MetaEvaCtestSumService metaEvaCtestSumService;
	@Autowired
	private MetaEvaCtestSumDao metaEvaCtestSumDao;
	
	/**
	 * 
	 * @param labelEvaCtestSum 标签实体
	 * @return 成功失败信息放入map中
	 */
	public Map<String, Object> insertLabelEvaCtestSum(LabelEvaCtestSum labelEvaCtestSum){
		Map<String, Object> modelMap = new HashMap<>();
		
		try {
			labelEvaCtestSumDao.insertLabelEvaCtestSum(labelEvaCtestSum);
			//updateLabelEvaCtestSum(labelEvaCtestSum.getId());
			modelMap.put("status", "success");
		} catch (BadSqlGrammarException e) {
			modelMap.put("status", "failed");
			//modelMap.put("msg", "数据格式出错"+"\n具体报错:"+e.getMessage());
			modelMap.put("msg", "数据格式出错:"+e.getMessage());
		} catch (DuplicateKeyException e) {
			modelMap.put("status", "failed");
			modelMap.put("msg", "违反唯一性约束");
		} catch (Exception e) {
			modelMap.put("status", "failed");
			modelMap.put("msg", "error class:" + e.getClass());
		}
		return modelMap;
	}
	
    /**
     * 
     * @param listId 序号组
     * @return 成功返回1，失败返回0
     */
    public int deleteLabelEvaCtestSum(List<Integer> listId) {
    	try {
    		for (Integer id : listId) {
    			entityEvaCtestSumDao.deleteEntityEvaCtestSumByLabelId(id);//组号为
    			labelEvaCtestSumDao.deleteLabelEvaCtestSum(id);
    			//updateLabelEvaCtestSum(id);
    		}
    		
    		return 1;
    	} catch (Exception e) {
    		e.printStackTrace();
    		return 0;
    	}finally {
    		//最终共同操作
    	}
    }
    
	/**
	 * 选出所有数据
	 * @return
	 */
	public ArrayList<LabelEvaCtestSum> queryLabelEvaCtestSum() {
		ArrayList<LabelEvaCtestSum> list = labelEvaCtestSumDao.queryLabelEvaCtestSum();
		return list;
	}
	
	/**
	 * 选出所有数据
	 * @return
	 * @throws JsonProcessingException 
	 */
	public List<Double> queryLabelEvaCtestSum2(int id) throws JsonProcessingException {
		List<String> list = new ArrayList<>();
		List<Column> cList = metaEvaCtestSumDao.selectColumn();
		List<Double> rs = new ArrayList<>();
		if(cList.isEmpty()) {
			rs.add(0.0);
			rs.add(0.0);
			return rs;
		}else {
			for (Column column : cList) {
				list.add(column.getEnName());
			}
		}
		
		//
		//1.将cList.enNamehe cList.csName->List<map>=listName map<csName,enName>
		//2.for ListName "城市污水再用水".equal(key) ->true get Map.getValue(csName) 得到英文名称
		//到 label enName对应的汇总数据
		
		//list.add("get_water");
//		list.add("use_water");
		Map<String, Object> paramSet = new HashMap<>();
		paramSet.put("linelist", list);
		
		paramSet.put("id", id);
		List<Map<String, Object>> resultMap = labelEvaCtestSumDao.queryLabelEvaCtestSum2(paramSet);
		//List<LabelEvaCtestSum> rs = new ArrayList<>();
		//LabelEvaCtestSum temp = new LabelEvaCtestSum();
		//第一组求和
		List<Column> clistAll = metaEvaCtestSumService.selectColumnNotByFlevel();
		int cnt1=metaEvaCtestSumService.queryColumnNumByFaLevel(1);
		int cnt2=metaEvaCtestSumService.queryColumnNumByFaLevel(2);
		int cnt3=metaEvaCtestSumService.queryColumnNumByFaLevel(3);
		int cnt4=metaEvaCtestSumService.queryColumnNumByFaLevel(4);
		int cnt5=metaEvaCtestSumService.queryColumnNumByFaLevel(5);

//		List<Column> clist1 = metaEvaCtestSumService.selectColumnByFlevel(1);
		List<Column> clist1 = clistAll.subList(0,cnt1);
		List<Column> clist2 = clistAll.subList(cnt1,cnt1+cnt2);
		List<Column> clist3 = clistAll.subList(cnt1+cnt2,cnt1+cnt2+cnt3);
		List<Column> clist4 = clistAll.subList(cnt1+cnt2+cnt3,cnt1+cnt2+cnt3+cnt4);
		
		double sum1 = 0;
		String str="";
		for (Column column : clist1) {
			rs.add(Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()));
			sum1 += Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString());
			str += column.getEnName() + "=" + "'" + Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()) + "'" + ","; 
		}
		
		//第二组求和
		//List<Column> clist2 = metaEvaCtestSumService.selectColumnByFlevel(2);
		double sum2 = 0;
		for (Column column : clist2) {
			rs.add(Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()));
			sum2 += Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString());
			str += column.getEnName() + "=" + "'" + Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()) + "'" + ",";
			//str += column.getEnName() + "=" + Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()) + ","; 
		}

//		//第三组求和
		//List<Column> clist3 = metaEvaCtestSumService.selectColumnByFlevel(3);
		double sum3 = 0;
		for (Column column : clist3) {
			rs.add(Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()));
			sum3 += Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString());
			str += column.getEnName() + "=" + "'" + Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()) + "'" + ",";
			//str += column.getEnName() + "=" + Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()) + ","; 
		}
//		
//		
//		//第四组求和
		//List<Column> clist4 = metaEvaCtestSumService.selectColumnByFlevel(4);
		//int sum4 = 0;
		for (Column column : clist4) {
			rs.add(Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()));
//			sum4 += (int)resultMap.get(0).get(column.getEnName());
			str += column.getEnName() + "=" + "'" + Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()) + "'" + ",";
			//str += column.getEnName() + "=" + Double.parseDouble(resultMap.get(0).get(column.getEnName().toUpperCase()).toString()) + ","; 
		}
		//赋值取水量总计
		String csName = "城镇污水再用水";
		if(metaEvaCtestSumService.isContainByCsName(csName)) {
			rs.add(sum1+Double.parseDouble(
					resultMap.get(0).get(
							metaEvaCtestSumService.queryMetaEvaCtestSumByCsName(csName).getEnName().toUpperCase())
					.toString()));
			str += "get_water=" + "'" +(sum1 + Double.parseDouble(
					resultMap.get(0).get(
							metaEvaCtestSumService.queryMetaEvaCtestSumByCsName(csName).getEnName().toUpperCase())
					.toString()))+ "'" +",";
//			str += "get_water=" + (sum1 + Double.parseDouble(
//					resultMap.get(0).get(
//							metaEvaCtestSumService.queryMetaEvaCtestSumByCsName(csName).getEnName().toUpperCase())
//					.toString()))+ ",";
		}else {
			rs.add(sum1);
			str += "get_water=" + "'" + (sum1) + "'" + ",";
		}
		DecimalFormat df=new DecimalFormat(".##");
		double d1=sum1+sum2+sum3;
		String st=df.format(d1);
		rs.add(Double.valueOf(st));
//		System.out.println(st);
		str += "use_water=" + "'" + (sum1 + sum2 + sum3) + "'" + ",water1_sum=" + "'" + sum1 + "'" + ",uncon_water_use=" + "'" + sum2 + "'";
		Map<String, Object> sqlMap = new HashMap<>();
		sqlMap.put("id", id);
		
		sqlMap.put("sql", str);
		labelEvaCtestSumDao.updateLabelEvaCtestSum2(sqlMap);
		return rs;
	}
	/**
	 * 更新描述字段
	 * @param labelEvaCtestSum 更新数据
	 * @return 成功返回1，失败返回0
	 */
	public int updateLabelEvaCtestSum(LabelEvaCtestSum labelEvaCtestSum) {
		try {
    		labelEvaCtestSumDao.updateLabelEvaCtestSum(labelEvaCtestSum);
    		return 1;
    	} catch (Exception e) {
    		e.printStackTrace();
    		return 0;
    	}finally {
    		//最终共同操作
    	}
	}
	
	
	/**
	 * 更新記錄
	 * @param id 記錄id
	 * @return 成功返回1，失败返回0
	 */
	public int updateLabelEvaCtestSum(int id) {
		String str1 = null;
		String str2 = null;
		String str3 = null;
		String str4 = null;
		String str = null;
		//第一组
		List<Column> list1 = metaEvaCtestSumDao.selectColumnByFlevel(1);
		for (Column column : list1) {
			str1 = column.enName + "_sum="+"sum("+column.enName+"),";
			str2 = "sum(" + column.enName+")+";
		}
		//第二组
		List<Column> list2 = metaEvaCtestSumDao.selectColumnByFlevel(2);
		for (Column column : list2) {
			str1 = column.enName + "_sum="+"sum("+column.enName+"),";
			str3 = "sum(" + column.enName+")+";
		}
		//第三组
		List<Column> list3 = metaEvaCtestSumDao.selectColumnByFlevel(3);
		for (Column column : list3) {
			str1 = column.enName + "_sum="+"sum("+column.enName+"),";
		}
		//第三组
		List<Column> list4 = metaEvaCtestSumDao.selectColumnByFlevel(4);
		for (Column column : list4) {
			str1 = column.enName + "_sum="+"sum("+column.enName+"),";
		}
		String csName = "城镇污水再用水";
		if(metaEvaCtestSumService.isContainByCsName(csName)) {
			String temp=null;
			try {
				temp = metaEvaCtestSumService.queryMetaEvaCtestSumByCsName(csName).getEnName();
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			str = str1 + "get_water=" + str2 + "sum(" + temp + ")"
			+",use_water=" + str2 + str3;
			str1 = str1.substring(0, str1.length()-1);
			str1 +=",water1_sum=" + str2;
			str1 = str1.substring(0, str1.length()-1);
		}else {
			str = str1 + "get_water=water1_sum=" + str2;
			str1 = str1.substring(0, str1.length()-1);
			str1 +=",use_water=" + str2 + str3;
			str1 = str1.substring(0, str1.length()-1);
		}
		Map<String, Object> sqlMap = new HashMap<>();
		sqlMap.put("id", id);
		sqlMap.put("sql", str);
		return labelEvaCtestSumDao.updateLabelEvaCtestSum2(sqlMap);
	}
	
	
}
